<template>
  <div class="editor-icon">
    <el-tabs v-model="activeName" @tab-change="reFolder">
      <el-tab-pane label="通用" name="default">
        <el-scrollbar style="height: calc(100vh - 91px);">
          <el-collapse v-model="activeCollapse" @change="onCollapse">
            <el-collapse-item name="common" v-if="oftenIcons">
              <template #title>
                <div class="collapse-title">
                  <i v-show="!isFolderOpened('common')" class="el-icon-folder"></i>
                  <i v-show="isFolderOpened('common')" class="el-icon-folder-opened"></i>
                  {{ `常用图形(${oftenIcons.length})` }}
                </div>
              </template>
              <div class="collapse-content" @dragstart="onDragstart($event, oftenIcons)">
                <div v-show="oftenIcons.length < 1" class="empty">
                  <span>暂无常用图标</span>
                </div>
                <div class="icon" v-for="(icon, index) in oftenIcons" :key="index" :data-index="index" draggable="true">
                  <i :class="`iconfont ${icon.icon}`" :title="icon.name" v-if="icon.icon?.indexOf('icon-') > -1"
                    :data-index="index"></i>
                  <i :class="`t-icon !w-[50px] !h-[50px] ${icon.icon}`" :title="icon.name" v-else-if="icon.icon"
                    :data-index="index"></i>
                  <!-- <img class="t-icon !w-[50px] !h-[50px]" :src="getAssetURL('../assets/resource' + icon.img)" v-else :data-index="index" /> -->
                  <img class="t-icon !w-[50px] !h-[50px] object-contain" :src="icon.img" v-else :data-index="index" />
                  <div class="w-full h-[20px] text-[14px] overflow-ellipsis"> {{ icon.name
                    }}
                  </div>
                </div>
              </div>
            </el-collapse-item>
            <el-collapse-item v-for="(group, index) in icons" :key="index" :name="group.groupName">
              <template #title>
                <div class="collapse-title">
                  <i v-show="!isFolderOpened(group.groupName)" class="el-icon-folder"></i>
                  <i v-show="isFolderOpened(group.groupName)" class="el-icon-folder-opened"></i>
                  {{ `${group.groupName}(${group.icons.length})` }}
                </div>
              </template>
              <div class="collapse-content" @dragstart="onDragstart($event, group.icons)">
                <div class="icon" v-for="(icon, index) in group.icons" :key="index" draggable="true"
                  :data-index="index">
                  <i :class="`iconfont ${icon.icon}`" :title="icon.name" v-if="icon.icon?.indexOf('icon-') > -1"
                    :data-index="index"></i>
                  <i :class="`t-icon !w-[50px] !h-[50px] ${icon.icon}`" :title="icon.name" v-else-if="icon.icon"
                    :data-index="index"></i>
                  <!-- <img class="t-icon !w-[50px] !h-[50px]" :src="getAssetURL('../assets/resource' + icon.img)" v-else :data-index="index" /> -->
                  <img class="t-icon !w-[50px] !h-[50px] object-contain" :src="icon.img" v-else :data-index="index" />
                  <div class="w-full h-[20px] text-[14px] overflow-ellipsis" :data-index="index">
                    {{ icon.name }}
                  </div>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-scrollbar>
      </el-tab-pane>
      <el-tab-pane label="拓扑" name="topo">
        <el-scrollbar style="height: calc(100vh - 91px);">
          <el-collapse v-model="activeCollapse" @change="onCollapse">
            <el-collapse-item v-for="(group, index) in topoIcons" :key="index" :name="group.groupName">
              <template #title>
                <div class="collapse-title">
                  <i v-show="!isFolderOpened(group.groupName)" class="el-icon-folder"></i>
                  <i v-show="isFolderOpened(group.groupName)" class="el-icon-folder-opened"></i>
                  {{ `${group.groupName}(${group.icons.length})` }}
                </div>
              </template>

              <div class="collapse-content" @dragstart="onDragstart($event, group.icons)">
                <div class="icon" v-for="(icon, index) in group.icons" :key="index" draggable="true"
                  :data-index="index">
                  <i :class="`iconfont ${icon.icon}`" :title="icon.name" v-if="icon.icon?.indexOf('icon-') > -1"
                    :data-index="index"></i>
                  <i :class="`t-icon !w-[50px] !h-[50px] ${icon.icon}`" :title="icon.name" v-else-if="icon.icon"
                    :data-index="index"></i>
                  <!-- <img class="t-icon !w-[50px] !h-[50px]" :src="getAssetURL('../assets/resource' + icon.img)" v-else :data-index="index" /> -->
                  <img class="t-icon !w-[50px] !h-[50px]" :src="icon.img" v-else :data-index="index" />
                  <div class="w-full h-[20px] text-[14px] overflow-ellipsis" :data-index="index">
                    {{ icon.name }}
                  </div>
                </div>
              </div>
            </el-collapse-item>
          </el-collapse>
        </el-scrollbar>
      </el-tab-pane>
      <el-tab-pane label="单位图库" name="unitLibrary">
        <el-scrollbar style="height: calc(100vh - 91px);">
          <div class="flex-bc gap-[16px] p-[16px]">
            <el-button v-auth="'business.graph.createGraphGroup'" class="flex-1" type="primary" :icon="Plus"
              @click="addFolders()">新建文件夹</el-button>
            <el-button v-auth="'business.graph.createGraph'" class="flex-1" type="primary" :icon="UploadFilled"
              :disabled="folderList.length == 0" @click="addMaterials()">上传图片</el-button>
          </div>
          <div v-if="folderList && folderList.length > 0">
            <el-collapse v-model="activeCustomCollapse" @change="onCollapse">
              <el-collapse-item v-for="(group, index) in folderList" :key="index"
                :name="`unitLibrary${group.groupName}`" @click="onCollapseItem(group)">
                <template #title>
                  <div class="collapse-title !px-[10px] w-full flex-bc gap-[16px]">
                    <div>
                      <i v-show="!isFolderOpened(group.groupName)" class="el-icon-folder"></i>
                      <i v-show="isFolderOpened(group.groupName)" class="el-icon-folder-opened"></i>
                      <!-- {{ `${group.groupName}(${group.graphCount})` }} -->
                      {{ `${group.groupName}` }}
                    </div>
                    <el-dropdown trigger="click">
                      <span class="hover:text-[var(--el-color-primary)]" @click.stop>
                        <el-icon>
                          <MoreFilled />
                        </el-icon>
                      </span>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item v-auth="'business.graph.updateGraphGroup'"
                            @click="editFolders(group)">编辑</el-dropdown-item>
                          <el-dropdown-item v-auth="'business.graph.removeGraphGroup'"
                            @click="deleteFolders(group)">删除</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                </template>
                <div class="custom">
                  <div v-loading="group?.isLoading" class="collapse-content"
                    @dragstart="onDragstart($event, group.graph)">
                    <div class="icon relative" v-for="(icon, index) in group.graph" :key="index" draggable="true"
                      :data-index="index">
                      <img class="t-icon !w-[75px] !h-[75px] object-contain" :src="icon.graphImage" :data-index="index" />
                      <div class="w-full h-[20px] text-[14px] px-[15px]  relative" :data-index="index">
                        <div class="w-[75.5px] h-full overflow-ellipsis whitespace-nowrap overflow-hidden"
                          v-if="!icon?.editName">
                          {{ icon.graphName }}
                        </div>
                        <el-input v-else class="w-full h-full" autofocus v-model="icon.graphName"
                          @blur="editGraphs(icon)" @change="editGraphs(icon)"></el-input>
                        <!-- <el-icon v-auth="'business.graph.updateGraph'"
                          class="!absolute right-[0px] top-[50%] translate-y-[-50%] "
                          style="visibility: var(--show-edit) ;" @click="icon.editName = true">
                          <EditPen />
                        </el-icon> -->
                      </div>
                      <!-- <el-icon v-auth="'business.graph.removeGraph'"
                        class="!text-[14px] !absolute right-[10px] top-[10px]" style="visibility: var(--show-edit) ;"
                        @click="deleteGraphs(icon)">
                        <Delete />
                      </el-icon> -->
                      <el-dropdown
                        v-if="haveRole('business.graph.updateGraph') || haveRole('business.graph.removeGraph')"
                        trigger="click" class="!text-[14px] !absolute right-[10px] top-[10px]">
                        <span class="hover:text-[var(--el-color-primary)]" @click.stop>
                          <el-icon>
                            <MoreFilled />
                          </el-icon>
                        </span>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item v-if="haveRole('business.graph.updateGraph')"
                              @click="addMaterials(2, 'edit', '编辑图片', icon)">编辑</el-dropdown-item>
                            <el-dropdown-item v-if="haveRole('business.graph.removeGraph')"
                              @click="deleteGraphs(icon)">删除</el-dropdown-item>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </div>
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
          <div v-else class="p-[16px] text-center text-[var(--el-text-color-secondary)]">
            暂无数据...
          </div>
        </el-scrollbar>
      </el-tab-pane>
      <el-tab-pane label="公共图库" name="commonLibrary">
        <el-scrollbar style="height: calc(100vh - 91px);">
          <div class="flex-bc gap-[16px] p-[16px]">
            <el-button v-auth="'business.topo.public'" class="flex-1" type="primary" :icon="Plus"
              @click="addFolders(1)">新建文件夹</el-button>
            <el-button v-auth="'business.topo.public'" class="flex-1" type="primary" :icon="UploadFilled"
              :disabled="commonFolderList.length == 0" @click="addMaterials(1)">上传图片</el-button>
          </div>
          <div v-if="commonFolderList && commonFolderList.length > 0">
            <el-collapse v-model="activeCustomCollapse" @change="onCollapse">
              <el-collapse-item v-for="(group, index) in commonFolderList" :key="index"
                :name="`commonLibrary${group.groupName}`" @click="onCollapseItem(group)">
                <template #title>
                  <div class="collapse-title !px-[10px] w-full flex-bc gap-[16px]">
                    <div>
                      <i v-show="!isFolderOpened(group.groupName)" class="el-icon-folder"></i>
                      <i v-show="isFolderOpened(group.groupName)" class="el-icon-folder-opened"></i>
                      <!-- {{ `${group.groupName}(${group.graphCount})` }} -->
                      {{ `${group.groupName}` }}
                    </div>
                    <el-dropdown v-auth="'business.topo.public'" trigger="click">
                      <span class="hover:text-[var(--el-color-primary)]" @click.stop>
                        <el-icon>
                          <MoreFilled />
                        </el-icon>
                      </span>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item @click="editFolders(group)">编辑</el-dropdown-item>
                          <el-dropdown-item @click="deleteFolders(group)">删除</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>

                  </div>
                </template>
                <div class="custom">
                  <div v-loading="group?.isLoading" class="collapse-content"
                    @dragstart="onDragstart($event, group.graph)">
                    <div class="icon relative" v-for="(icon, index) in group.graph" :key="index" draggable="true"
                      :data-index="index">
                      <img class="t-icon !w-[75px] !h-[75px] object-contain" :src="icon.graphImage" :data-index="index" />
                      <div class="w-full h-[20px] text-[14px] px-[15px]  relative" :data-index="index">
                        <div class="w-[75.5px] h-full overflow-ellipsis whitespace-nowrap overflow-hidden"
                          v-if="!icon?.editName">
                          {{ icon.graphName }}
                        </div>
                        <el-input v-else class="w-full h-full" autofocus v-model="icon.graphName"
                          @blur="editGraphs(icon)" @change="editGraphs(icon)"></el-input>
                        <!-- <el-icon v-auth="'business.topo.public'"
                          class="!absolute right-[0px] top-[50%] translate-y-[-50%] "
                          style="visibility: var(--show-edit) ;" @click="icon.editName = true">
                          <EditPen />
                        </el-icon> -->
                      </div>
                      <!-- <el-icon v-auth="'business.topo.public'" class="!text-[14px] !absolute right-[10px] top-[10px]"
                        style="visibility: var(--show-edit) ;" @click="deleteGraphs(icon)">
                        <Delete />
                      </el-icon> -->
                      <el-dropdown v-auth="'business.topo.public'" trigger="click"
                        class="!text-[14px] !absolute right-[10px] top-[10px]">
                        <span class="hover:text-[var(--el-color-primary)]" @click.stop>
                          <el-icon>
                            <MoreFilled />
                          </el-icon>
                        </span>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item @click="addMaterials(1, 'edit', '编辑图片', icon)">编辑</el-dropdown-item>
                            <el-dropdown-item @click="deleteGraphs(icon)">删除</el-dropdown-item>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </div>
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
          <div v-else class="p-[16px] text-center text-[var(--el-text-color-secondary)]">
            暂无数据...
          </div>
        </el-scrollbar>
      </el-tab-pane>
      <el-tab-pane label="单位模板" name="unitTemplate" v-if="configurationPageStores.source != 'manage'">
        <el-scrollbar style="height: calc(100vh - 91px);">
          <div v-if="templateFolderList && templateFolderList.length > 0">
            <el-collapse v-model="activeCustomCollapse" @change="onCollapse">
              <el-collapse-item v-for="(group, index) in templateFolderList" :key="index"
                :name="`unitTemplate${group.groupName}`" @click="getTemplateItem(group)">
                <template #title>
                  <div class="collapse-title !px-[10px] w-full flex-bc gap-[16px]">
                    <div>
                      <i v-show="!isFolderOpened(group.groupName)" class="el-icon-folder"></i>
                      <i v-show="isFolderOpened(group.groupName)" class="el-icon-folder-opened"></i>
                      <!-- {{ `${group.groupName}(${group.graphCount})` }} -->
                      {{ `${group.groupName}` }}
                    </div>
                    <!-- <el-dropdown trigger="click">
                      <span class="hover:text-[var(--el-color-primary)]" @click.stop>
                        <el-icon>
                          <MoreFilled />
                        </el-icon>
                      </span>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item v-auth="'business.graph.updateTplGroup'"
                            @click="editTemplateFolders(group)">编辑</el-dropdown-item>
                          <el-dropdown-item v-auth="'business.graph.removeTplGroup'"
                            @click="deleteTemplateFolders(group)">删除</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
          </el-dropdown> -->
                  </div>
                </template>
                <div class="custom">
                  <div v-loading="group?.isLoading" class="collapse-content">
                    <div class="icon relative" v-for="(icon, index) in group.list" :key="index" draggable="true"
                      :data-index="index">
                      <img class="t-icon !w-[75px] !h-[75px] object-contain" :src="icon.topoImg" :data-index="index" />
                      <div class="w-full h-[20px] text-[14px] px-[15px]  relative" :data-index="index">
                        <div class="w-[75.5px] h-full overflow-ellipsis whitespace-nowrap overflow-hidden"
                          v-if="!icon?.editName">
                          {{ icon.topoName }}
                        </div>
                        <el-input v-else class="w-full h-full" autofocus v-model="icon.topoName"
                          @blur="editTemplateItems(icon)" @change="editTemplateItems(icon)"></el-input>
                        <!-- <el-icon v-auth="'business.graph.updatetpl'"
                          class="!absolute right-[0px] top-[50%] translate-y-[-50%] " @click="icon.editName = true">
                          <EditPen />
                        </el-icon> -->
                      </div>
                      <!-- <el-icon class="!text-[14px] !absolute right-[10px] top-[10px]"
                        style="visibility: var(--show-edit) ;" @click="deleteTemplateItems(icon)">
                        <Delete />
                      </el-icon> -->
                      <el-dropdown trigger="click" class="!text-[14px] !absolute right-[10px] top-[10px]">
                        <span class="hover:text-[var(--el-color-primary)]" @click.stop>
                          <el-icon>
                            <MoreFilled />
                          </el-icon>
                        </span>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item @click="useTemplate(icon)">使用</el-dropdown-item>
                            <!-- <el-dropdown-item v-auth="'business.graph.updatetpl'"
                              @click="edtiTemplate(icon)">编辑</el-dropdown-item> -->
                            <!-- <el-dropdown-item v-if="haveRole('business.graph.updatetpl')"
                              @click="addTemplates(2, 'edit', '编辑模板', icon)">编辑</el-dropdown-item>
                            <el-dropdown-item v-if="haveRole('business.graph.removetpl')"
                              @click="deleteTemplateItems(icon)">删除</el-dropdown-item> -->
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </div>
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
          <div v-else class="p-[16px] text-center text-[var(--el-text-color-secondary)]">
            暂无数据...
          </div>
        </el-scrollbar>
      </el-tab-pane>
      <el-tab-pane label="公共模板" name="commonTemplate" v-if="configurationPageStores.source != 'manage'">
        <el-scrollbar style="height: calc(100vh - 91px);">
          <div v-if="commonTemplateFolderList && commonTemplateFolderList.length > 0">
            <el-collapse v-model="activeCustomCollapse" @change="onCollapse">
              <el-collapse-item v-for="(group, index) in commonTemplateFolderList" :key="index"
                :name="`commonTemplate${group.groupName}`" @click="getTemplateItem(group)">
                <template #title>
                  <div class="collapse-title !px-[10px] w-full flex-bc gap-[16px]">
                    <div>
                      <i v-show="!isFolderOpened(group.groupName)" class="el-icon-folder"></i>
                      <i v-show="isFolderOpened(group.groupName)" class="el-icon-folder-opened"></i>
                      <!-- {{ `${group.groupName}(${group.graphCount})` }} -->
                      {{ `${group.groupName}` }}
                    </div>
                    <!-- <el-dropdown v-auth="'business.topo.public'" trigger="click">
                      <span class="hover:text-[var(--el-color-primary)]" @click.stop>
                        <el-icon>
                          <MoreFilled />
                        </el-icon>
                      </span>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item @click="editTemplateFolders(group)">编辑</el-dropdown-item>
                          <el-dropdown-item @click="deleteTemplateFolders(group)">删除</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
          </el-dropdown> -->
                  </div>
                </template>
                <div class="custom">
                  <div v-loading="group?.isLoading" class="collapse-content">
                    <div class="icon relative" v-for="(icon, index) in group.list" :key="index" draggable="true"
                      :data-index="index">
                      <img class="t-icon !w-[75px] !h-[75px] object-contain" :src="icon.topoImg" :data-index="index" />
                      <div class="w-full h-[20px] text-[14px] px-[15px]  relative" :data-index="index">
                        <div class="w-[75.5px] h-full overflow-ellipsis whitespace-nowrap overflow-hidden"
                          v-if="!icon?.editName">
                          {{ icon.topoName }}
                        </div>
                        <el-input v-else class="w-full h-full" autofocus v-model="icon.topoName"
                          @blur="editTemplateItems(icon)" @change="editTemplateItems(icon)"></el-input>
                        <!-- <el-icon v-auth="'business.topo.public'"
                          class="!absolute right-[0px] top-[50%] translate-y-[-50%] " @click="icon.editName = true">
                          <EditPen />
                        </el-icon> -->
                      </div>
                      <!-- <el-icon class="!text-[14px] !absolute right-[10px] top-[10px]"
                        style="visibility: var(--show-edit) ;" @click="deleteTemplateItems(icon)">
                        <Delete />
                      </el-icon> -->
                      <el-dropdown trigger="click" class="!text-[14px] !absolute right-[10px] top-[10px]">
                        <span class="hover:text-[var(--el-color-primary)]" @click.stop>
                          <el-icon>
                            <MoreFilled />
                          </el-icon>
                        </span>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item @click="useTemplate(icon)">使用</el-dropdown-item>
                            <!-- <el-dropdown-item v-if="haveRole('business.topo.public')"
                              @click="addTemplates(1, 'edit', '编辑模板', icon)">
                              编辑
                            </el-dropdown-item>
                            <el-dropdown-item v-if="haveRole('business.topo.public')"
                              @click="deleteTemplateItems(icon)">
                              删除
                            </el-dropdown-item> -->
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </div>
                  </div>
                </div>
              </el-collapse-item>
            </el-collapse>
          </div>
          <div v-else class="p-[16px] text-center text-[var(--el-text-color-secondary)]">
            暂无数据...
          </div>
        </el-scrollbar>
      </el-tab-pane>
    </el-tabs>

  </div>
</template>

<script setup lang="ts">
import { IconGroups, TopoIcons } from '../constant'
import { useTopologyEditorStore } from '@/store/modules/topology-editor'
import { ElMessageBox, type CollapseActiveName, type CollapseModelValue } from 'element-plus'
import { Plus, MoreFilled, EditPen, Delete, DocumentAdd, UploadFilled } from "@element-plus/icons-vue";
import { addDialog } from "@/components/ReDialog";
import { cloneDeep, deviceDetection } from "@pureadmin/utils";
import { customPromiseDebounce, haveRole } from "@/utils/functions";
import { getGroup, addFolder, editFolder, deleteFolder, addMaterial, editGraph, getTopoPic, deleteGraph } from '@/api/topo/index'
import { getTemplateGroup, addTemplateFolder, editTemplateFolder, deleteTemplateFolder, getTemplate, addTemplate, deleteTemplate, editTemplate } from '@/api/topo/index'
import folderForm from './components/folderForm.vue'
import graphForm from './components/graphForm.vue'
import templateForm from './components/templateForm.vue'
import { message } from '@/utils/message';
import { reHttpAndWebsocket } from '../utils';
import { configurationPageStore } from '@/store/modules/configurationPage';
defineOptions({
  name: 'EditorProps'
})
const activeName = ref('default')
const store = useTopologyEditorStore()
const configurationPageStores = configurationPageStore()
const unityId = configurationPageStores.unityId
const topoId = configurationPageStores.topoId
const icons = reactive(IconGroups)
const topoIcons = reactive(TopoIcons)
let activeCollapse: CollapseActiveName[] = ['基本形状']
const activeCustomCollapse = ref([])
const oftenIcons = store.oftenIcons
const formRef = ref()
const folderList = ref([])
const commonFolderList = ref([])
const templateFolderList = ref([])
const commonTemplateFolderList = ref([])
onMounted(() => {
  getFolders()
  if (configurationPageStores.source != 'manage') {
    getTemplateFolders()
  }
})
function isFolderOpened(name: CollapseActiveName) {
  return activeCollapse.includes(name)
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function onDragstart(e: DragEvent, icons: any[]) {
  const index = e.target && e.target instanceof HTMLElement ? Number(e.target.dataset['index']) : -1
  if (index > -1) {
    const icon = icons[index]
    e.dataTransfer?.setData('Text', JSON.stringify(icon.pen ?? icon.graphData.pen))
    store.addOftenIcon(icon)
  }
}
function onCollapse(activeNames: CollapseModelValue) {
  activeCollapse = activeNames as CollapseActiveName[]
}
const getFolders = () => {
  getGroup({ unityId: unityId }).then(res => {
    folderList.value = cloneDeep(res.result.data).filter(item => {
      return item.isPublic == 2
    })
    commonFolderList.value = cloneDeep(res.result.data).filter(item => {
      return item.isPublic == 1
    })
    reFolder()
  })
}
const getTemplateFolders = () => {
  getTemplateGroup({ unityId: unityId }).then(res => {
    templateFolderList.value = cloneDeep(res.result.data).filter(item => {
      return item.isPublic == 2
    })
    commonTemplateFolderList.value = cloneDeep(res.result.data).filter(item => {
      return item.isPublic == 1
    })
    reFolder()
  })
}
const reFolder = () => {
  if (activeName.value == 'unitLibrary') {
    folderList.value.forEach(item => {
      if (activeCustomCollapse.value.includes(`unitLibrary${item.groupName}`)) {
        onCollapseItem(item)
      }
    })
  } else if (activeName.value == 'commonLibrary') {
    commonFolderList.value.forEach(item => {
      if (activeCustomCollapse.value.includes(`commonLibrary${item.groupName}`)) {
        onCollapseItem(item)
      }
    })
  } else if (activeName.value == 'unitTemplate') {
    templateFolderList.value.forEach(item => {
      if (activeCustomCollapse.value.includes(`unitTemplate${item.groupName}`)) {
        getTemplateItem(item)
      }
    })
  } else if (activeName.value == 'commonTemplate') {
    commonTemplateFolderList.value.forEach(item => {
      if (activeCustomCollapse.value.includes(`commonTemplate${item.groupName}`)) {
        getTemplateItem(item)
      }
    })
  }
}
const onCollapseItem = (row) => {
  if (row?.isOpen) return;
  row.isLoading = true
  getTopoPic({
    unityId: unityId,
    groupId: row.id
  }).then(res => {
    row.graph = res.result.data
  }).finally(() => {
    row.isOpen = true
    row.isLoading = false
  })
}
const addFolders = (isPublic = 2) => {
  if (isPublic == 2) {
    openForm('新建文件夹', 'add')
  } else if (isPublic == 1) {
    openPublicForm('新建文件夹', 'add')
  }
}
const editFolders = (row) => {
  openForm('编辑文件夹', 'edit', 'folder', row)
}
const deleteFolders = (row) => {
  ElMessageBox.confirm('此操作将永久删除该文件夹, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteFolder({
      unityId: unityId,
      id: row.id
    }).then(res => {
      message('删除成功', { type: 'success' })
      getFolders()
    })
  }).catch(() => {
    message('已取消删除', { type: 'info' })
  })
}
const addMaterials = (isPublic = 2, type = 'add', title = '上传图片', row?) => {
  if (isPublic == 2) {
    openForm(title, type, 'material', row)
  } else if (isPublic == 1) {
    openPublicForm(title, type, 'material', row)
  }
}
const editGraphs = (row) => {
  if (row.editName) {
    row.unityId = unityId
    editGraph(row).then(res => {
      if (res.code == 200) {
        message(res.msg, { type: 'success' })
        folderList.value.forEach(item => {
          if (item.id == row.groupId) {
            item.isOpen = false
            onCollapseItem(item)
            return
          }
        })
      }
    }).finally(() => {
      row.editName = false
    })
  }
}
const deleteGraphs = (row) => {
  ElMessageBox.confirm('此操作将永久删除该图片, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteGraph({
      unityId: unityId,
      id: row.id
    }).then(res => {
      message('删除成功', { type: 'success' })
      if (activeName.value == 'unitLibrary') {
        folderList.value.forEach(item => {
          if (item.id == row.groupId) {
            item.isOpen = false
            onCollapseItem(item)
            return
          }
        })
      } else if (activeName.value == 'commonLibrary') {
        commonFolderList.value.forEach(item => {
          if (item.id == row.groupId) {
            item.isOpen = false
            onCollapseItem(item)
            return
          }
        })
      }
      // getFolders()
    })
  }).catch(() => {
    message('已取消删除', { type: 'info' })
  })
}
const openForm = (title, type, content = 'folder', editRow?) => {
  addDialog({
    title: title,
    width: "400px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    props: {
      formInline: {}
    },
    contentRenderer: () => h(content == 'folder' ? folderForm : graphForm, { ref: formRef }),
    openAutoFocus({ options, index }) {
      if (content == 'folder') {
        if (type == 'edit') {
          options.props.formInline = cloneDeep(editRow)
        } else {
          options.props.formInline = {
            groupName: '',
            isPublic: 2
          }
        }
      } else {
        if (type == 'edit') {
          options.props.formInline = cloneDeep(editRow)
          options.props.formInline.unityId = unityId
          options.props.formInline.isPublic = 2
        } else {
          options.props.formInline = {
            unityId: unityId,
            isPublic: 2
          }
        }
      }
    },
    beforeSure: (done, { options }) => {
      const FormRef = formRef.value.getRef();
      const formData = options.props.formInline;
      formData.unityId = unityId
      function chores() {
        message(`操作成功`, {
          type: "success"
        });
        getFolders()
        done();
      }
      FormRef.validate(valid => {
        if (valid && !options.props?.isLoading) {
          options.props.isLoading = true;
          if (type == 'add') {
            (content == 'folder' ? DebounceAddFolder(formData) : DebounceAddMaterial(formData)).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          } else {
            (content == 'folder' ? DebounceEditFolder(formData) : DebounceEditGraph(formData)).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          }
        }
      });
    }
  });
}
const openPublicForm = (title, type, content = 'folder', editRow?) => {
  addDialog({
    title: title,
    width: "400px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    props: {
      formInline: {}
    },
    contentRenderer: () => h(content == 'folder' ? folderForm : graphForm, { ref: formRef }),
    openAutoFocus({ options, index }) {
      if (content == 'folder') {
        if (type == 'edit') {
          options.props.formInline = cloneDeep(editRow)
        } else {
          options.props.formInline = {
            groupName: '',
            isPublic: 1
          }
        }
      } else {
        if (type == 'edit') {
          options.props.formInline = cloneDeep(editRow)
          options.props.formInline.unityId = unityId
        } else {
          options.props.formInline = {
            unityId: unityId,
            isPublic: 1
          }
        }
      }
    },
    beforeSure: (done, { options }) => {
      const FormRef = formRef.value.getRef();
      const formData = options.props.formInline;
      formData.unityId = unityId
      function chores() {
        message(`操作成功`, {
          type: "success"
        });
        getFolders()
        done();
      }
      FormRef.validate(valid => {
        if (valid && !options.props?.isLoading) {
          options.props.isLoading = true;
          if (type == 'add') {
            (content == 'folder' ? DebounceAddFolder(formData) : DebounceAddMaterial(formData)).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          } else {
            (content == 'folder' ? DebounceEditFolder(formData) : DebounceEditGraph(formData)).then(res => {
              if (res.code == 200) {
                chores();
              }
              options.props.isLoading = false;
            }).catch((err) => {
              if (err !== '请求中') {
                options.props.isLoading = false;
              }
            })
          }
        }
      });
    }
  });
}
const addTemplateFolders = (isPublic = 2) => {
  openTemplateForm('新建文件夹', 'add', isPublic)
}
const editTemplateFolders = (row, isPublic = 2) => {
  openTemplateForm('编辑文件夹', 'edit', isPublic, 'folder', row)
}
const addTemplates = (isPublic = 2, type = 'add', title = '保存模板', row?) => {
  openTemplateForm(title, type, isPublic, 'template', row)
}
const deleteTemplateFolders = (row) => {
  ElMessageBox.confirm('此操作将永久删除该文件夹, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteTemplateFolder({
      unityId: unityId,
      id: row.id
    }).then(res => {
      message('删除成功', { type: 'success' })
      getTemplateFolders()
    })
  }).catch(() => {
    message('已取消删除', { type: 'info' })
  })
}
const getTemplateItem = (row) => {
  if (row?.isOpen) return;
  row.isLoading = true
  getTemplate({ unityId: unityId, id: row.id }).then(res => {
    row.list = res.result.data
  }).finally(() => {
    row.isOpen = true
    row.isLoading = false
  })
}
const editTemplateItems = (row) => {
  if (row.editName) {
    row.unityId = unityId
    editTemplate(row).then(res => {
      if (res.code == 200) {
        message(res.msg, { type: 'success' })
        folderList.value.forEach(item => {
          if (item.id == row.groupId) {
            item.isOpen = false
            onCollapseItem(item)
            return
          }
        })
      }
    }).finally(() => {
      row.editName = false
    })
  }
}
const deleteTemplateItems = (row) => {
  ElMessageBox.confirm('此操作将永久删除该文件夹, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteTemplate({
      unityId: unityId,
      id: row.id
    }).then(res => {
      message('删除成功', { type: 'success' })
      if (activeName.value == 'unitTemplate') {
        templateFolderList.value.forEach(item => {
          if (item.id == row.groupId) {
            item.isOpen = false
            getTemplateItem(item)
            return
          }
        })
      } else if (activeName.value == 'commonTemplate') {
        commonTemplateFolderList.value.forEach(item => {
          if (item.id == row.groupId) {
            item.isOpen = false
            getTemplateItem(item)
            return
          }
        })
      }
    })
  }).catch(() => {
    message('已取消删除', { type: 'info' })
  })
}
const openTemplateForm = (title, type, isPublic = 2, content = 'folder', editRow?) => {
  addDialog({
    title: title,
    width: "400px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    props: {
      formInline: {}
    },
    contentRenderer: () => h(content == 'folder' ? folderForm : templateForm, { ref: formRef }),
    openAutoFocus({ options, index }) {
      if (content == 'folder') {
        if (type == 'edit') {
          options.props.formInline = cloneDeep(editRow)
        } else {
          options.props.formInline = {
            groupName: '',
            isPublic: isPublic
          }
        }
      } else {
        // if (!store.editTemplate) {
        if (type == 'add') {
          options.props.formInline = {
            unityId: unityId,
            isPublic: isPublic
          }
        } else {
          options.props.formInline = cloneDeep(editRow)
          // options.props.formInline = store.editTemplate
          options.props.formInline.isSaveCurrent = false
          options.props.formInline.isPublic = isPublic
        }
      }
    },
    beforeSure: (done, { options }) => {
      const FormRef = formRef.value.getRef();
      const formData = options.props.formInline;
      formData.unityId = unityId
      function chores() {
        message(`操作成功`, {
          type: "success"
        });
        getTemplateFolders()
        done();
      }
      FormRef.validate(valid => {
        if (valid && !options.props?.isLoading) {
          options.props.isLoading = true;
          if (content == 'folder') {
            if (type == 'add') {
              DebounceAddTemplateFolder(formData).then(res => {
                if (res.code == 200) {
                  chores();
                }
                options.props.isLoading = false;
              }).catch((err) => {
                if (err !== '请求中') {
                  options.props.isLoading = false;
                }
              })
            } else {
              DebounceEditTemplateFolder(formData).then(res => {
                if (res.code == 200) {
                  chores();
                }
                options.props.isLoading = false;
              }).catch((err) => {
                if (err !== '请求中') {
                  options.props.isLoading = false;
                }
              })
            }
          } else {
            const data = window.meta2d.data()
            let blob = ''
            try {
              blob = window.meta2d.toPng(0, undefined, true, 150)
            } catch (err) { }
            // if (!store.editTemplate) {
            if (type == 'add') {
              formData.topoData = data
              formData.topoImg = blob
              DebounceAddTemplate(formData).then(res => {
                if (res.code == 200) {
                  chores();
                }
                options.props.isLoading = false;
              }).catch((err) => {
                if (err !== '请求中') {
                  options.props.isLoading = false;
                }
              })
            } else {
              formData.topoData = formData.isSaveCurrent ? data : JSON.parse(formData.topoData)
              formData.topoImg = formData.isSaveCurrent ? blob : formData.topoImg
              DebounceEditTemplate(formData).then(res => {
                if (res.code == 200) {
                  chores();
                }
                options.props.isLoading = false;
              }).catch((err) => {
                if (err !== '请求中') {
                  options.props.isLoading = false;
                }
              })
            }
          }
          // if (type == 'add') {
          //   (content == 'folder' ? DebounceAddTemplateFolder(formData) : DebounceAddTemplate(formData)).then(res => {
          //     if (res.code == 200) {
          //       chores();
          //     }
          //     options.props.isLoading = false;
          //   }).catch((err) => {
          //     if (err !== '请求中') {
          //       options.props.isLoading = false;
          //     }
          //   })
          // } else {
          //   (content == 'folder' ? DebounceEditTemplateFolder(formData) : DebounceEditTemplate(formData)).then(res => {
          //     if (res.code == 200) {
          //       chores();
          //     }
          //     options.props.isLoading = false;
          //   }).catch((err) => {
          //     if (err !== '请求中') {
          //       options.props.isLoading = false;
          //     }
          //   })
          // }
        }
      });
    }
  });
}
const useTemplate = (row) => {
  // store.editTemplate = row
  window.meta2d.open(JSON.parse(row.topoData))
  // window.meta2d.setGrid({
  //   grid: true,
  //   gridColor: '#e2e2e2',
  //   gridSize: 20,
  //   gridRotate: 0
  // })
  // window.meta2d.setRule({
  //   rule: true,
  //   ruleColor: '#888888'
  // })
  window.meta2d.lock(0)
  // store.editTemplate = row
  reHttpAndWebsocket()
}
const edtiTemplate = (row) => {
  store.editTemplate = row
  window.meta2d.open(JSON.parse(row.topoData))
  window.meta2d.setGrid({
    grid: true,
    gridColor: '#e2e2e2',
    gridSize: 20,
    gridRotate: 0
  })
  window.meta2d.setRule({
    rule: true,
    ruleColor: '#888888'
  })
  window.meta2d.lock(0)
  reHttpAndWebsocket()
}
const DebounceAddFolder = customPromiseDebounce(addFolder, 1000, true);
const DebounceEditFolder = customPromiseDebounce(editFolder, 1000, true);
const DebounceAddMaterial = customPromiseDebounce(addMaterial, 1000, true);
const DebounceEditGraph = customPromiseDebounce(editGraph, 1000, true);

const DebounceAddTemplateFolder = customPromiseDebounce(addTemplateFolder, 1000, true);
const DebounceEditTemplateFolder = customPromiseDebounce(editTemplateFolder, 1000, true);
const DebounceAddTemplate = customPromiseDebounce(addTemplate, 1000, true);
const DebounceEditTemplate = customPromiseDebounce(editTemplate, 1000, true);

</script>

<style lang="scss" scoped>
@import '@/components/TopologyEditor/assets/editor-variable.scss';

:deep(.el-tabs__header) {
  margin: 0;
}

.editor-icon {
  :deep(.el-tabs__item) {
    padding-left: 20px !important;
  }
}

:deep(.el-collapse) {
  margin-bottom: 50px;
}

.empty {
  width: 100%;
  font-size: 12px;
  color: #afafaf;
  text-align: center;
}

.collapse-title {
  padding: 0 0 0 10px;
}

.custom {
  .collapse-content {
    min-height: 100px;
    padding: 0 19px;
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-auto-rows: 125.5px;
    gap: 10px;
    align-items: center;
    justify-content: center;
  }
}

.collapse-content {
  padding: 0 19px;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  align-items: center;
  //flex-wrap: wrap;
  //margin: auto;
}

.icon {
  --show-edit: hidden;
  width: 100%;
  height: 100%;
  text-align: center;
  display: flex;
  flex-direction: column;
  margin: 0;
  padding: 10px;
  cursor: pointer;
  gap: 10px;
  justify-content: center;
  align-items: center;
  border-radius: 5px;
  color: $--editor-text-color;
}

.icon:hover {
  --show-edit: none;
}

.l-icon {
  width: 30px;
  height: 30px;
  border-radius: 3px;
}

.icon:hover {
  background-color: $--editor-icon-hover-color;
}

.icon>i {
  // height: 24px;
  font-size: 24px;
}

:deep(.el-collapse-item__content) {
  padding: 0px 0 10px;
}

.iconfont {
  color: rgba(0, 0, 0, 0.5);
}
</style>
